import * as Request from '../request';
import { IndustryRankMap } from '@config/map';
import { RankTOOL } from '@utils/index';

// 专利增长趋势 柱状图数据处理
const PatentCreateFormat = (res) => {
  // 将数据按照x轴（年份）进行排序
  const sortedData = res?.data.sort((a, b) => a.apy - b.apy);

  const getArrData = (key) => {
    return Array.from(new Set(sortedData?.map((c) => c[key])));
  };

  const getYear = (key) => {
    return Array.from(new Set(sortedData?.map((c) => Number(c[key]))));
  };

  const legendData = getArrData('name'); // 获取类型数据

  const xAxisData = getYear('apy'); // x轴数据： 所有年份，已排序
  const series = legendData.map((legend) => {
    // 过滤当前 legend(patent_type) 的数据
    const oneTypeLegendArr = sortedData.filter((c) => c.name === legend);

    // 按照年份遍历出y轴对应的值
    const treatedData = xAxisData.map((year) => {
      const filteredObj = oneTypeLegendArr.find((data) => Number(data.apy) === year) || {};
      const labelStr = filteredObj.value || 0;
      return labelStr === 'NaN' ? '无' : labelStr;
    });

    return {
      name: legend,
      barWidth: 22,
      stack: 'total',
      label: {
        show: true,
        textStyle: {
          color: '#FCFCFCFF',
          fontSize: 16,
        },
      },
      data: treatedData,
      type: 'bar',
    };
  });

  return {
    legendData,
    xAxisData,
    series,
  };
};

// 企业资质
export const QualificationAPI = async (params) => {
  const url = '/api/qulification/all';
  let res: any;
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  sessionStorage.setItem('cxy', '' + res?.find?.((r) => r.code === '产学研载体')?.value ?? '-'); //   产学研载体数

  return res.data;
};

// 专利增长趋势
export const PatentTrendAPI = async (params) => {
  const url = '/api/patent/trend';
  let res: any;
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  return PatentCreateFormat(res);
};

// 一区两中心
export const SeicAPI = async (params) => {
  const url = '/api/seic/patent_cnt';
  let res: any;
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  return res.data;
};

// 产业排名
export const IndustryRankAPI = async (params) => {
  const url = '/api/company/analysis';
  let res: any;
  try {
    res = await Request.post(url, params);
  } catch (error) {
    console.log('request error:', url, error);
  }

  const data = IndustryRankMap.map((i: any) => {
    const item = res?.data.find((r) => r.name === i.name);
    i.value = item?.value;
    return i;
  });
  const sortedData = RankTOOL(data ?? [], 'value');

  return sortedData;
};
